//
//  ShareMangaer.m
//  CoolMove
//
//  Created by CA on 14-12-4.
//  Copyright (c) 2014年 CA. All rights reserved.
//

#import "ShareMangaer.h"
#import "WXApi.h"
#import <TencentOpenAPI/QQApiInterface.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import "FlatUIKit.h"
#import "FUIAlertView+customizeAppearance.h"
#import "UIImage+ImageFromView.h"

@implementation ShareMangaer

+ (instancetype)sharedInstance
{
    static id sharedInstance = nil;
    static dispatch_once_t oncePredicate;
    
    dispatch_once(&oncePredicate, ^{
        sharedInstance = [[self alloc] init];
    });
    
    return sharedInstance;
}

- (void)shareInView:(UIView *)view
        withContent:(NSString *)content
      imageFromView:(UIView *)imageInView
          shareType:(SSDKPlatformType)type
   shareResultBlock:(ShareResultBlock)block
{
    if (type == SSDKPlatformSubTypeWechatSession || type == SSDKPlatformSubTypeWechatTimeline) {
        if (![WXApi isWXAppInstalled]) {
            [self showInstallApplicationPlatformTipsWithShareType:type];
            return;
        }
    } else if (type == SSDKPlatformSubTypeQQFriend || type == SSDKPlatformSubTypeQZone) {
        if (![QQApiInterface isQQInstalled]) {
            [self showInstallApplicationPlatformTipsWithShareType:type];
            return;
        }
    }
    
    UIImage *image = [UIImage imageFromView:imageInView];
    if ([imageInView isKindOfClass:[UIScrollView class]]) {
        image = [self captureScrollView:(UIScrollView *)imageInView];
    }
    

    
    NSBundle*bundle =[NSBundle mainBundle];
    NSDictionary*info =[bundle infoDictionary];
    NSString*appName =[info objectForKey:@"CFBundleDisplayName"];
    
    NSArray* imageArray = nil;
    if (image != nil) {
        imageArray = @[image];
    }
    
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:content
                                     images:imageArray
                                        url:[NSURL URLWithString:@"http://www.coollang.com"]
                                      title:appName
                                       type:SSDKContentTypeAuto];
    
    [ShareSDK share:type parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        switch (state) {
            case SSDKResponseStateSuccess:
            {
                block(YES);
                break;
            }
            case SSDKResponseStateFail:
            {
                block(NO);
                break;
            }
            default:
                break;
        }
    }];
}

- (void)shareInView:(UIView *)view
        withContent:(NSString *)content
              image:(UIImage *)image
          shareType:(SSDKPlatformType)type
   shareResultBlock:(ShareFinishBlock)block
{
    if (type == SSDKPlatformSubTypeWechatSession || type == SSDKPlatformSubTypeWechatTimeline) {
        if (![WXApi isWXAppInstalled]) {
            [self showInstallApplicationPlatformTipsWithShareType:type];
            block(NO,@"请安装微信");
            return;
        }
    } else if (type == SSDKPlatformSubTypeQQFriend || type == SSDKPlatformSubTypeQZone) {
        if (![QQApiInterface isQQInstalled]) {
            [self showInstallApplicationPlatformTipsWithShareType:type];
            block(NO,@"请安装QQ");
            return;
        }
    }
    
    NSBundle*bundle =[NSBundle mainBundle];
    NSDictionary*info =[bundle infoDictionary];
    NSString*appName =[info objectForKey:@"CFBundleDisplayName"];
    
    NSArray* imageArray = nil;
    if (image != nil) {
        imageArray = @[image];
    }
    
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    if (type == SSDKPlatformSubTypeQZone) {
        UIImage *image;
        if (imageArray&&imageArray.count>0) {
            image = imageArray[0];
        }
        
        [shareParams SSDKSetupQQParamsByText:nil title:@"智能轮滑" url:[NSURL URLWithString:@"http://www.coollang.com"] thumbImage:image image:image type:SSDKContentTypeWebPage forPlatformSubType:SSDKPlatformSubTypeQZone];
    }else{
        [shareParams SSDKSetupShareParamsByText:content
                                         images:imageArray
                                            url:[NSURL URLWithString:@"http://www.coollang.com"]
                                          title:appName
                                           type:SSDKContentTypeImage];
    }
    
    
    [ShareSDK share:type parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        switch (state) {
            case SSDKResponseStateSuccess:
            {
                block(YES,@"分享成功");
                break;
            }
            case SSDKResponseStateFail:
            {
                block(NO,@"分享失败");
                break;
            }
            case SSDKResponseStateCancel:
            {
                block(NO,nil);
                break;
            }
            case SSDKResponseStateBegin:
                break;
        }
    }];
}

- (void)shareInView:(UIView *)view
        withContent:(NSString *)content
          withTitle:(NSString *)title
            withUrl:(NSString *)url
          shareType:(SSDKPlatformType)type
   shareResultBlock:(ShareResultBlock)block
{
    if (type == SSDKPlatformSubTypeWechatSession || type == SSDKPlatformSubTypeWechatTimeline) {
        if (![WXApi isWXAppInstalled]) {
            [self showInstallApplicationPlatformTipsWithShareType:type];
            return;
        }
    } else if (type == SSDKPlatformSubTypeQQFriend || type == SSDKPlatformSubTypeQZone) {
        if (![QQApiInterface isQQInstalled]) {
            [self showInstallApplicationPlatformTipsWithShareType:type];
            return;
        }
    }
    

    
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
//    [shareParams SSDKSetupShareParamsByText:content
//                                     images:nil
//                                        url:[NSURL URLWithString:@"http://www.coollang.com"]
//                                      title:title
//                                       type:SSDKContentTypeAuto];
    
    NSURL *urlShare = [NSURL URLWithString:url];
    switch (type) {
        case SSDKPlatformSubTypeQZone:
            [shareParams SSDKSetupQQParamsByText:content title:title url:urlShare thumbImage:nil image:[UIImage imageNamed:@"app_icon_share"] type:SSDKContentTypeAuto forPlatformSubType:SSDKPlatformSubTypeQZone];
            break;
        case SSDKPlatformSubTypeQQFriend:
            [shareParams SSDKSetupQQParamsByText:content title:title url:urlShare thumbImage:nil image:[UIImage imageNamed:@"app_icon_share"] type:SSDKContentTypeAuto forPlatformSubType:SSDKPlatformSubTypeQQFriend];
            break;
        case SSDKPlatformSubTypeWechatSession:
            [shareParams SSDKSetupWeChatParamsByText:content title:title url:urlShare thumbImage:nil image:[UIImage imageNamed:@"app_icon_share"]  musicFileURL:nil extInfo:nil fileData:nil emoticonData:nil type:SSDKContentTypeAuto forPlatformSubType:type];
        case SSDKPlatformSubTypeWechatTimeline:
            [shareParams SSDKSetupWeChatParamsByText:content title:title url:urlShare thumbImage:nil image:[UIImage imageNamed:@"app_icon_share"]  musicFileURL:nil extInfo:nil fileData:nil emoticonData:nil type:SSDKContentTypeAuto forPlatformSubType:type];
        default:
            break;
    }
    
    [ShareSDK share:type parameters:shareParams onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
        switch (state) {
            case SSDKResponseStateSuccess:
            {
                block(YES);
                break;
            }
            case SSDKResponseStateFail:
            {
                block(NO);
                break;
            }
            default:
                block(NO);
                break;
        }
    }];
}


#pragma mark - Private Method

- (UIImage *)captureScrollView:(UIScrollView *)scrollView{
    UIImage* image = nil;
    UIGraphicsBeginImageContext(scrollView.contentSize);
    {
        CGPoint savedContentOffset = scrollView.contentOffset;
        CGRect savedFrame = scrollView.frame;
        scrollView.contentOffset = CGPointZero;
        scrollView.frame = CGRectMake(0, 0, scrollView.contentSize.width, scrollView.contentSize.height);
        
        [scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        
        scrollView.contentOffset = savedContentOffset;
        scrollView.frame = savedFrame;
    }
    UIGraphicsEndImageContext();
    
    if (image != nil) {
        return image;
    }
    return nil;
}

- (void)showInstallApplicationPlatformTipsWithShareType:(SSDKPlatformType)type
{
    FUIAlertView *alertView = nil;
    if (type == SSDKPlatformSubTypeQQFriend || type == SSDKPlatformSubTypeQZone) {
        alertView = [[FUIAlertView alloc] initWithTitle:@"提醒" message:@"用户没有安装\"QQ\"应用，请前往Appstore下载安装" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"返回", nil];
        /*
        alertView.onOkAction = ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/qq/id444934666?mt=8"]];
        };
         */
    } else if (type == SSDKPlatformSubTypeWechatSession || type == SSDKPlatformSubTypeWechatTimeline) {
        alertView = [[FUIAlertView alloc] initWithTitle:@"提醒" message:@"用户没有安装\"微信\"应用，请前去Appstore下载安装" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"返回", nil];
        /*
        alertView.onOkAction = ^{
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/wei-xin/id414478124?mt=8"]];
        };
         */
    }
    
    [alertView customizeAppearance];
    [alertView show];
}

@end
